﻿using System;
using System.Collections.Generic;
using System.Web;
using MeTalker.Securitys.Cryptography;
using System.Text;
using MeTalker.BLL;
using MeTalker.Model;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Web.SessionState;
using System.Data;
using MeTalker.DAL;
/// <summary>
///RequestLoginHandlerBase 的摘要说明
/// </summary>
public class RequestLoginHandlerBase : HandlerBase
{
    protected void InitRequest(string type, string dataType, string sid, string info, string soft,string userName)
    {
        //MembersBLL.Insert(new MembersMod() { LicenseDate = DateTime.Now, LoginFlag = false, Memo = "Memo", MobilePhone = "MobilePhone", Password = "Password", RegistDate = DateTime.Now, SessionId = "SessionId", LatestOnline = DateTime.Now, AddDate = DateTime.Now, ExpireDate = DateTime.Now, Email = "Email", UserType = "UserType", SoftName = "SoftName", SoftID = "SoftID", QQ = "QQ", UserName = "UserName", IsValid = false, HDID = "HDID" });
        try
        {
            switch (type)
            {
                case TYPE_USER_LICENSE:
                    {
                        List<MembersMod> members = MembersBLL.GetFilterToList(" SessionId='" + sid + "'");
                        if (members == null || members.Count <= 0)
                            members = MembersBLL.GetFilterToList(" UserName='" + userName + "'");
                        if (members != null && members.Count > 0)
                        {
                            WriteLicense(members[0]);
                        }
                        else
                        {
                            Write(SYSTEM_FAIL);
                        }
                        break;
                    }
                case TYPE_USER_REG:
                    {
                        #region 注册
                        //Write(FAIL);
                        //return;
                        int size = Request.ContentLength;
                        byte[] b = new byte[size];
                        Request.InputStream.Read(b, 0, b.Length);

                        //b = aes.Decrypt(b);
                        //string xml = Encoding.UTF8.GetString(b);
                        string xml = DecryptToString(dataType, b);
                        int len = xml.Length;
                        if(len<=9){
                            return;
                        }
                        string temp2 = xml.Substring(0,8);
                         if (!temp2.Equals(CONST_FLAG)) {
                            return;
                        }
                        xml = xml.Substring(8, len-8);

                        using (StringReader reader = new StringReader(xml))
                        {
                            XDocument doc = XDocument.Load(reader);
                            var ds = from temp in doc.Descendants()
                                     select new MembersMod()
                                     {
                                         UserName = temp.Element("Uid") != null ? temp.Element("Uid").Value : "",
                                         Password = temp.Element("Pass") != null ? temp.Element("Pass").Value : "",
                                         HDID = temp.Element("HD") != null ? Base64Tostring(temp.Element("HD").Value) : "",
                                         Email = temp.Element("Email") != null ? temp.Element("Email").Value : "",

                                         QQ = temp.Element("QQ") != null ? temp.Element("QQ").Value : "",
                                         MobilePhone = temp.Element("Tel") != null ? temp.Element("Tel").Value : "",
                                     };
                            MembersMod membes = ds.FirstOrDefault();
                            membes.Password = GetMD5(membes.Password);
                            SoftwaresMod software = SoftwaresBLL.GetSoftware(soft);
                            int errcode=0;
                            if (MembersBLL.CheckUserName(membes.UserName, software.SoftID, out errcode))
                            {
                                Write(USER_EXIST);
                                return;
                            }
                            //if (MembersBLL.CheckHDID(membes.HDID))
                            //{
                            //    Write(REG_DOUBLE);
                            //    return;
                            //}

                            
                            membes.RegistDate = DateTime.Now;
                            membes.ExpireDate = DateTime.Now.AddDays(software.TrialDays);
                            membes.LoginFlag = false;
                            membes.IsValid = true;
                            membes.Memo = "";
                            membes.SessionId = Session.SessionID;
                            membes.AddDate = membes.RegistDate;
                            membes.UserType = "0";
                            membes.SoftID = software.SoftID;
                            membes.SoftName = software.SoftName;
                            //DataTable dt = MembersBLL.GetUsers(membes);
                            MembersMod temp1 = MembersBLL.CheckSoftHD(membes);
                            if (temp1 != null)
                            {
                                Write(REG_DOUBLE + ",u=" + temp1.UserName);
                                return;
                            }
                            if (software.SoftID.Equals("JL0001"))
                            {
                                if (MembersBLL.Insert(membes) > 0)
                                {
                                    Write(SUCCESS);
                                }
                                else
                                {
                                    Write(FAIL);
                                }
                            }
                            else
                            {
                                Write(FAIL);
                            }
                        }
                        break;
                        #endregion
                    }
                case TYPE_USER_HEART:
                    {
                        string sessionId = Session.SessionID;
                        MembersBLL.Heart(soft, sid);
                        Write("sid=" + sessionId);
                        break;
                    }
                case TYPE_USER_LOGOUT:
                    {
                        MembersBLL.Logout(userName, soft);
                        break;
                    }
                case TYPE_USER_LOGIN:
                    {
                        #region 登录验证
                        //List<MembersMod> member = MembersBLL.SignUser("UserName", "Password");
                        int size = Request.ContentLength;
                        byte[] b = new byte[size];
                        Request.InputStream.Read(b, 0, b.Length);

                        //b = aes.Decrypt(b);
                        //string xml = Encoding.UTF8.GetString(b);
                        string xml = DecryptToString(dataType, b);
                        int len = xml.Length;
                        if (len <= 9)
                        {
                            return;
                        }
                        string temp2 = xml.Substring(0, 8);
                        if (!temp2.Equals(CONST_FLAG))
                        {
                            return;
                        }
                        xml = xml.Substring(8, len - 8);

                        using (StringReader reader = new StringReader(xml))
                        {
                            XDocument doc = XDocument.Load(reader);
                            var ds = from temp in doc.Descendants()
                                     select new MembersMod()
                                     {
                                         UserName = temp.Element("UD") != null ? temp.Element("UD").Value : "",
                                         Password = temp.Element("PD") != null ? temp.Element("PD").Value : "",
                                         HDID = temp.Element("HD") != null ? Base64Tostring(temp.Element("HD").Value) : "",
                                         SessionId = temp.Element("SID") != null ? temp.Element("SID").Value : "",
                                     };
                            MembersMod members = ds.FirstOrDefault();
                            if (members != null)
                            {
                                int errcode = 0;
                                members.SoftID = soft;
                                members.Password = GetMD5(members.Password);
                                if (!MembersBLL.CheckUserName(members.UserName, soft, out errcode))
                                {
                                    if (DALBase.DATA_ERROR == errcode) Write(errcode);
                                    else Write(USER_NOT_EXIST);
                                    return;
                                }
                                MembersMod member = MembersBLL.SignUser(members);
                                if (member != null)
                                {
                                    double timeMinutes = GetMinutes(DateTime.Now, member.LatestOnline);
                                    if (timeMinutes >= 0 && timeMinutes > LOGIN_FLAG_TIME_OUT)
                                    {
                                        member.LoginFlag = false;
                                    }
                                    //if (!member.SoftID.Equals(soft))
                                    //{
                                    //    Write(USER_NOT_EXIST);//账号未找到
                                    //}
                                     if (member.IsValid == false)
                                    {
                                        Write(USER_INVALID);//账号禁用
                                    }
                                    else if (GetDay(DateTime.Now, member.ExpireDate) > 0)
                                    {
                                        Write(LOGIN_OVER_VALID);//软件过期时间
                                    }
                                    else if (DateTime.Compare(DateTime.Now, member.ExpireDate) >= 0)
                                    {
                                        Write(LOGIN_OVER_VALID);//软件过期时间
                                    }
                                    else if (member.LoginFlag)
                                    {
                                        //if (member.IsValid && DateTime.Compare(DateTime.Now, member.ExpireDate) <= 1)
                                        if (member.IsValid)
                                        {
                                            if (members.SessionId.Equals(member.SessionId))// || GetMinutes(DateTime.Now, member.LatestOnline) > LOGIN_FLAG_TIME_OUT)
                                            {
                                                WriteUserLogin(dataType, member);
                                            }
                                            else
                                            {
                                                Write(LOGIN_DOUBLE);//帐户重复登录
                                            }
                                        }
                                        else
                                        {
                                            Write(LOGIN_DOUBLE);//帐户重复登录
                                        }
                                    }
                                    else if (member.IsValid && !member.LoginFlag)
                                    {
                                        WriteUserLogin(dataType, member);
                                    }
                                }
                                else
                                {
                                    Write(LOGIN_FAIL);//未找到当前用户
                                    return;
                                }
                                //if (!MembersBLL.CheckUserName(members.UserName))
                                //{
                                //    Write(USER_NOT_EXIST);
                                //    return;
                                //}
                                //MembersMod member = MembersBLL.SignUser(members);
                                //if (member != null)
                                //{
                                //    if (GetMinutes(DateTime.Now, member.LatestOnline) > LOGIN_FLAG_TIME_OUT)
                                //    {
                                //        member.LoginFlag = false;
                                //    }
                                //    if (member.SoftID.Equals(soft))
                                //    {
                                //        Write(USER_NOT_EXIST);//账号禁用
                                //    }
                                //    else if (member.IsValid == false)
                                //    {
                                //        Write(USER_INVALID);//账号禁用
                                //    }
                                //    else if (GetDay(DateTime.Now, member.ExpireDate) > 0)
                                //    {
                                //        Write(LOGIN_OVER_VALID);//软件过期时间
                                //    }
                                //    else if (DateTime.Compare(DateTime.Now, member.ExpireDate) > 0)
                                //    {
                                //        Write(LOGIN_OVER_VALID);//软件过期时间
                                //    }
                                //    else if (member.LoginFlag)
                                //    {
                                //        if (member.IsValid && DateTime.Compare(DateTime.Now, member.ExpireDate) <= 1)
                                //        {
                                //            if (members.SessionId.Equals(member.SessionId))// || GetMinutes(DateTime.Now, member.LatestOnline) > LOGIN_FLAG_TIME_OUT)
                                //            {
                                //                WriteUserLogin(dataType, member);
                                //            }
                                //            else
                                //            {
                                //                Write(LOGIN_DOUBLE);//帐户重复登录
                                //            }
                                //        }
                                //        else
                                //        {
                                //            Write(LOGIN_DOUBLE);//帐户重复登录
                                //        }
                                //    }
                                //    else if (member.IsValid && DateTime.Compare(DateTime.Now, member.ExpireDate) <= 1 && !member.LoginFlag)
                                //    {
                                //        WriteUserLogin(dataType, member);
                                //    }
                                //}
                                //else
                                //{
                                //    Write(LOGIN_FAIL);//未找到当前用户
                                //    return;
                                //}
                            }
                        }
                        #endregion
                        break;
                    }
            }
        }
        catch {
            Write(SYSTEM_FAIL);
        }
    }
}